package com.bw.lib_net.interceptor

import com.bw.lib_storage.UserMMKV
import okhttp3.Interceptor
import okhttp3.Response

/**
 * Token拦截器
 */
class TokenInterceptor: Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request().newBuilder()
            .addHeader("token",UserMMKV.token)
            .build()

        var response = chain.proceed(request)
        //判断token是否过期
        if (response.code.toString().startsWith("401")){
            //有感：发送全局事件，跳转到登录页面
            //无感：
            //1:访问刷新token接口，传入refresh_token
            //2：判断响应码是否为401：
            //2-1:401跳转到发送全局事件：跳转到登录页面
            //2-2:200返回新的access_token和refresh_token,保存到mmkv
            request = request.newBuilder()
                .addHeader("token",UserMMKV.token)//UserMMKV.token
                .build()

            response = chain.proceed(request)
        }

        return response
    }
}